package com.jay.bookkeep.vm
import com.app.baselibrary.base.BaseViewModel
import com.app.baselibrary.http.HttpResultException
import com.app.baselibrary.http.flow.HttpFlow
import com.app.baselibrary.ktx.runUI
import com.app.baselibrary.ktx.shortToast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import java.io.Closeable

/**
 * 数据仓库基类
 */
abstract class BaseHttpRepo(private val viewModel: BaseViewModel) : Closeable, CoroutineScope
by CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) {
    init {
        viewModel.setTagIfAbsent(this)
    }
    @Suppress("LeakingThis")
    fun lifecycleDialogHttpFlow(
        title: String = "",
        isShow: Boolean = true,
        mNetStatusResult: BaseViewModel.NetStatusResult?=null,
        httpFlow: HttpFlow,
    ): HttpFlow {
        return httpFlow.onStart {
//            ToastUtil.canceToast()
            if (isShow){
                if (title.isEmpty()) {
                    viewModel.showProgress()
                } else {
                    viewModel.showProgress(title)
                }
            }
        }.onException{
            codeHandle(this,mNetStatusResult)
        }.onComplete {
            viewModel.hideProgress()
        }
    }

    @Suppress("LeakingThis")
    fun lifecycleHttpFlow(
        mNetStatusResult: BaseViewModel.NetStatusResult?=null,
        httpFlow: HttpFlow,
        ): HttpFlow {
        return httpFlow.onStart {
//       ToastUtil.canceToast()
        }.onException{
            codeHandle(this,mNetStatusResult)
         } .onComplete {
        }
    }

    override fun close() {
        cancel()
    }

    /**
     * 状态码处理
     */
    fun codeHandle(httpResultException: HttpResultException, mNetStatusResult: BaseViewModel.NetStatusResult?=null) {
        val res_code=httpResultException.code
        if(res_code!=200){
            shortToast(httpResultException.message)
        }
        if(res_code==401||res_code==400){
            //重新登录
            runUI{

            }
        }else{
            if(httpResultException.message.contains("当前网络不可用~")||
                httpResultException.message.contains("网络连接异常")){
                mNetStatusResult?.onNetResult(true)
            }else{
                mNetStatusResult?.onServiceResult(true)
            }
        }
    }
}